package edu.gmu.hodum.sei.bluetooth;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Observable;
import java.util.Observer;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;

public class BluetoothIntentConn extends Observable implements Runnable, Observer{
	private BluetoothSocket btSoc;

	BluetoothIntentConn(Observer observer, BluetoothSocket btSoc){
		this.addObserver(observer);
		this.btSoc = btSoc;
	}
	
	//sends intents on the bluetooth socket
	public void sendIntent(Intent intent){
		
		if(btSoc!=null){
			SerialIntent serialIntent = new SerialIntent(intent);
			try {
				ObjectOutputStream outStream = new ObjectOutputStream(btSoc.getOutputStream());
				outStream.writeObject(serialIntent);
			} catch (IOException e) {
				System.out.println("");
				e.printStackTrace();
			}
		}
	}
	public BluetoothDevice getBluetoothDevice(){
		return btSoc.getRemoteDevice();
	}
	
	@Override
	public void run() {
		new ListenThread(this, btSoc);
		
	}
	//passes intent from Bluetooth socket
	@Override
	public void update(Observable arg0, Object arg1) {		
		this.update(arg0, arg1);
	}
	
	//listens for intents on the Bluetooth socket
	private class ListenThread extends Observable implements Runnable {
		private BluetoothSocket btSoc;
		
		ListenThread(Observer observer, BluetoothSocket btSoc){
			this.addObserver(observer);
			this.btSoc = btSoc;
		}
		@Override
		public void run() {
			try {
				//inputstream setup
				InputStream inStream = btSoc.getInputStream();
				ObjectInputStream objInStream = new ObjectInputStream(inStream);
				
				//main listening loop
				while (true){
					//read for objects
					Object o = objInStream.readObject();
					
					//if the object read is a SerialIntent, convert back into intent and pass to Observers
					if (o instanceof SerialIntent){
						Intent intent = ((SerialIntent)o).getIntent();
						this.notifyObservers(intent);
					}
				}
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
}


